import Vue from 'vue'
import Vuex from 'vuex'

// 1.安裝插件
Vue.use(Vuex)

const moduleA = {
  state: {
    name: 'kobe'
  },
  mutations: {},
  getters: {},
  actions: {}
}

// 2.创建对象
const store = new Vuex.Store({
  // 数据
  state: {
    counter: 10,
    name: 'beiysd'
  },
  // 方法
  mutations: {
    increment(state) {
      state.counter++
    },
    decrement(state) {
      state.counter--
    },
    // 外部传参
    incrementCounter(state, num) {
      state.counter += num
    },
    updateInfo(state) {
      state.name = 'skobell'
    }
  },

  // 计算属性
  getters: {
    powerCounter(state) {
      return Math.pow(state.counter, 2)
    },
    // 外部传参
    powerNumCounter(state, getters) {
      return num => {
        return getters.powerCounter * num
      }
    }
  },
  actions: {
    // context = store
    // 1.普通写法
    // aUpdateInfo(context, obj) {
    //   setTimeout(() => {
    //     console.log('payload===', obj.payload)
    //     obj.success()
    //     context.commit('updateInfo')

    //   }, 1000)
    // }

    // 2.promise写法
    aUpdateInfo(context, payload) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          console.log('payload===', payload)
          context.commit('updateInfo')
          resolve('返回给组件的信息')
        })
      })
    }
  },
  modules: {
    a: moduleA,
    b: {
      state: {},
      mutations: {},
      getters: {},
      actions: {}
    }
  }
})

// 3.导出store独享
export default store
